package org.tio.freemarker.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.freemarker.TioWebpackWebServerStarter;
import org.tio.freemarker.compress.css.TioCssCompressor;
import org.tio.freemarker.compress.html.TioHtmlCompressor;
import org.tio.freemarker.compress.js.TioJsCompressor;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.common.MimeType;
import org.tio.http.common.RequestLine;
import org.tio.http.server.intf.HttpServerInterceptor;

/**
 * @author tanyaowu 
 * 2017年11月17日 下午3:09:27
 */
public class TioWebpackHttpServerInterceptor implements HttpServerInterceptor {
	private static Logger log = LoggerFactory.getLogger(TioWebpackHttpServerInterceptor.class);

	/**
	 * 
	 * @author tanyaowu
	 */
	public TioWebpackHttpServerInterceptor() {
	}

	/**
	 * TODO 注意：本处的实现并未过多考虑性能
	 * @param request
	 * @param requestLine
	 * @param response
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public void doAfterHandler(HttpRequest request, RequestLine requestLine, HttpResponse response) throws Exception {
		if (response == null) {
			return;
		}
		String contentType = response.getContentType();

		if (contentType == null) {
			return;
		}

		MimeType mimeType = MimeType.fromType(contentType);

		if (mimeType != null) {
			String extension = mimeType.getExtension();
			
			if ("js".equalsIgnoreCase(extension)) {
				if (TioWebpackWebServerStarter.model.getCompress().getJs()) {
					String initStr = new String(response.getBody(), request.getCharset());
					String compressedStr = TioJsCompressor.compress(requestLine.getPath(), initStr);
					response.setBody(compressedStr.getBytes(request.getCharset()), request);
				}
			} else if ("css".equalsIgnoreCase(extension)) {
				if (TioWebpackWebServerStarter.model.getCompress().getCss()) {
					String initStr = new String(response.getBody(), request.getCharset());
					String compressedStr = TioCssCompressor.compress(requestLine.getPath(), initStr);
					response.setBody(compressedStr.getBytes(request.getCharset()), request);
				}
			} else if ("html".equalsIgnoreCase(extension) || "htm".equalsIgnoreCase(extension)) {
				if (TioWebpackWebServerStarter.model.getCompress().getHtml()) {
					String initStr = new String(response.getBody(), request.getCharset());
					String compressedStr = TioHtmlCompressor.compress(requestLine.getPath(), initStr);
					response.setBody(compressedStr.getBytes(request.getCharset()), request);
				}
			}
		}
	}

	/** 
	 * @param packet
	 * @param requestLine
	 * @param httpResponseFromCache
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public HttpResponse doBeforeHandler(HttpRequest request, RequestLine requestLine, HttpResponse responseFromCache) throws Exception {
		return null;
	}

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {

	}
}
